<?php
namespace User\Controller;

use Common\Controller\WeixinController;

class LoginController extends WeixinController
{
    // 登录验证提交
    public function dologin()
    {
        $wx_user   = D("WxUser");
        $post_data = I('post.');
        $code      = I('post.code/s');
        if (!$code) {
            $this->ajaxReturn(['code' => 40000, 'msg' => 'code不能为空']);
        }
        //并发控制
        $cacheKey = 'cacheLoginControllerDologin';
        while (S($cacheKey) > 1000) {
            sleep(1);
        }

        //记录任务
        $cache = S($cacheKey);
        S($cacheKey, $cache + 1, ['expire' => 30]);
        //业务开始
        $res_wx = $this->send_url(['code' => $code]);
        $res_wx = json_decode($res_wx, true);
        if ($res_wx['errcode']) {
            $this->ajaxReturn(['code' => 50000, 'msg' => 'code失效']);
        }
        $post_data['openid']  = $res_wx['openid'] ?? '';
        $post_data['unionid'] = $res_wx['unionid'] ?? '';

        //检查用户是否存在
        $user_info = $wx_user->field('id,status')->where("openid='%s' ", [$post_data['openid']])->find();
        $type      = $user_info['id'] ? 2 : 1;
        $post_data = $wx_user->create($post_data, $type);
        if (!$post_data) {
            $this->ajaxReturn(['code' => 40000, 'msg' => $wx_user->getError()]);
        }
        if (isset($post_data['amount'])) {
            unset($post_data['amount']);
        }
        if (isset($post_data['frozen_amount'])) {
            unset($post_data['frozen_amount']);
        }

        if ($user_info['id']) {
            $last_id = $user_info['id'];
            $wx_user->where(['id' => $last_id])->save($post_data);
        } else {
            $last_id = $wx_user->add($post_data);
        }
        $session_user_info = md5($post_data['openid'] . $last_id);
        $token             = md5($post_data['openid'] . $last_id . time() . microtime());
        //设置登录信息
        $post_data['user_id'] = $last_id;
        $post_data['status'] = $user_info['status'];
        S($token, $session_user_info, ['expire' => 86400 * 30]);
        S($session_user_info, $post_data, ['expire' => 86400 * 30]);
        //配置信息
        $config = $this->configInfo($last_id);
        //释放缓存
        $cache = S($cacheKey);
        S($cacheKey, $cache - 1, ['expire' => 30]);
        $this->ajaxReturn(['code' => 20000, 'msg' => 'success', 'token' => $token, 'config' => $config]);
    }

    // 配置信息
    private function configInfo($last_id = 0)
    {
        $rule = "1.活动时间:2月8日0:00-3月2日18:00（元宵节）,用户通过向朋友发起集字讨彩头或生成分享图到朋友圈,请朋友助力送字。";
        $rule .= "2.获得送字数量多前100名用户将上排行榜,3月2日20:00系统将自动将100万奖金发放至用户余额中。";
        $rule .= "3.活动期间, 每日同一组彩头同一个人发送的同一个字只记录一次为有效字数统计。本次活动最终解释权归新年讨彩头所有!";
        $helpList = [
            [
                'tit' => "集字瓜分百万奖金规则",
                'txt' => $rule
            ],
            [
                'tit' => "新年讨彩头怎么玩？",
                'txt' => "选择一个新年好彩头，向朋友发起集字送祝福，好友可随机或选字并随机塞入赏金，集齐祝福字可获得相应的赏金。"
            ],
            [
                'tit' => "我发起了讨彩头但是没发出去？",
                'txt' => "请到主页的【我的记录】中找到发起的记录，点击【求送字】可把彩头祝福转发给好友或群，也可以生成朋友圈分享图发朋友圈。"
            ],
            [
                'tit' => "如何提现到微信钱包？",
                'txt' => "在主页的【余额提现】或详情页的【去提现】均可跳转至余额提现页面进行提现，提现金额每次至少" . C('MIN_WITHDRAWALS') . "元，每天最多提现" . C('MAX_WITHDRAWAL_TIME') . "次。"
            ],
            [
                'tit' => "提现会收取服务费吗？多久到账？",
                'txt' => "提现会收取" . C('WITHDRAWAL_RATIO') . "%的手续费；申请提现后会在1-5个工作日内转账到您的微信钱包。"
            ],
            [
                'tit' => "如何联系客服？",
                'txt' => "小程序不提供客服服务，如需人工客服请搜索公众号新年讨彩头（客服在线时间：9:00-23:00）。"
            ],
        ];
        //刷单者
        $barkerMoner = [
            0 => '0.68',
            1 => '0.88',
            2 => '1.58',
            3 => '1.68',
            4 => '13.14',
            5 => '1.88',
            6 => '5.20',
            7 => '5.20',
            8 => '6.66',
            9 => '6.68',
            10 => '6.88',
            11 => '8.66',
            12 => '8.68',
            13 => '8.88',
            14 => '13.14',
        ];
        $barker = $this->getBarker();

        $config = [
            'wishes'        => C('WISH_CONTENT'),
            'feed_backs'    => C('WISH_FEED_BACKS'),
            'moneys'        => in_array($last_id,$barker) ? $barkerMoner:C('WISH_MONEY'),
            'img_base_url'  => C('IMG_BASE_URL'),
            'news_key'      => $last_id > 40 ? C('news_key') : '',
            'balance_adv'   => $this->getAdv('withdrawal'),
            'help_adv'      => $this->getAdv('cquestion'),
            'help_list'     => $helpList,
            'check_version' => C('CHECK_VERSION'),
            'tip_message'   => C('TIP_MESSAGE'),
            'demoKoulin'    => ['集齐新年彩头获得赏金'],//C('DEMO_KOULIN'),
            'act_message'   => '“集字瓜分百万奖金”活动火爆开启！快邀请朋友助力集字吧！可查看排行榜关注排名！活动规则请参见“常见问题”',
        ];

        return $config;
    }

    private function getBarker(){
        $cacheKey = 'cachegetBarker';
        //获取缓存
        $cache = S($cacheKey);
        if ($cache) {
            return $cache;
        }else{
            return [];
        }
    }

    /*
     * 获取指定位置广告
     * 传入下标
     */
    public function getAdv($pos)
    {
        $cacheKey = 'cacheGetAdv' . $pos;
        //获取缓存
        $cache = S($cacheKey);
        if ($cache) {
            return $cache;
        }
        $slideModel = M('slide');
        $adv        = $slideModel
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'slide_cat b ON slide_cid=b.cid')
            ->field('*')
            ->where(['cat_idname' => $pos, 'cat_status' => 1, 'slide_status' => 1])
            ->select();

        if (empty($adv)) {
            return null;
        }

        foreach ($adv as $k => $v) {
            $adv[$k]['slide_pic'] = 'https://' . $_SERVER['HTTP_HOST'] . C("TMPL_PARSE_STRING.__UPLOAD__") . $v['slide_pic'];
        }

        if ($pos != 'index3') {
            $adv = $adv[0];
        }
        //设置缓存
        S($cacheKey, $adv, ['expire' => 3600]);

        return $adv;
    }

    // 配置信息
    public function config()
    {
        $config = [
            'check_version' => C('CHECK_VERSION'),
        ];

        $this->ajaxReturn(['code' => 20000, 'msg' => 'success', 'data' => $config]);
    }
}